import { deleteById, updateAddress } from '@mall/api/address'
import router from "@src/router";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: mall,
    fields: ['chooseAddress'],
    actions:['deteChooseAddress']
  }],
  properties: {
    hiddenOperate: {
      type: Boolean,
      value: true
    },
    tempAddress: {
      type: Object,
    },
    operateType: {
      type: String,
    },
    operateText: {
      type: Object
    }
  },
  options: {
    addGlobalClass: true,
  },

  /**
   * 组件的初始数据
   */
  data: {

    nowCursor: 0,

  },

  /**
   * 组件生命周期
   */
  lifetimes: {

    attached: function (val) {


    },
    ready: function (val) {


    },
    moved: function () {

    },
    detached: function () {

    },
  },

  /**
 * 组件所在页面生命周期
 */
  pageLifetimes: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    setHiddentrue() {
      this.setData({
        hiddenOperate: true
      })

    },
    //删除地址
    deteteAddress() {
      const that = this;
      //type为edit就是删除地址，为search就是先逛逛

      if (this.data.operateType == 'edit') {
        deleteById(this.data.tempAddress.id).then(res => {
          console.log(res)
          if (res.code === 0) {
            this.deteChooseAddress()
            wx.showToast({
              title: '设置成功',
              icon: 'success',
              duration: 2000
            })

          } else {
            wx.showToast({
              title: res.msg
            })
          }
          that.setHiddentrue()
          //向父组件发出刷新列表的事件
          this.triggerEvent('refreshList')
        })
      } else {
        that.setHiddentrue()
      }
    },

    //设为默认地址
    setDefalutAddress() {
      const that = this;
      //TODO 这里进行判断，然后再决定向父组件发出什么事件
      //type为edit就是设置为默认地址，为search就是添加为收货地址
      if (this.data.operateType == 'search') {
        let tempObj = JSON.stringify(this.data.tempAddress);
        console.log('tempObj', tempObj)
        that.setHiddentrue()
        //向父组件发出隐藏事件
        this.triggerEvent('hiddenOperateFunc')
        router.push({name: 'mall/address-form', params: {mode: 'add', addressStr: tempObj}})
      } else {
        let temp = that.data.tempAddress
        temp.defaulted = true
        updateAddress(temp).then(res => {
          if (res.code === 0) {
            wx.showToast({
              title: '设置成功',
              icon: 'success',
              duration: 2000
            })
          }
          that.setHiddentrue()
          //向父组件发出刷新列表的事件
          that.triggerEvent('refreshList')
        })

      }

    }




  }
})
